#!/bin/bash
# 请在需要使用hooks的工程根目录下执行该脚本

WORK_SPACE_PATH=$(pwd)
PARENT_DIR_PATH=$(cd $(dirname $0);pwd)
THIS_SHELL_PATH="$PARENT_DIR_PATH/$(basename $0)"

source "$PARENT_DIR_PATH/hooks/common.sh"

JQ_URL_LINUX_64="https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64"
JQ_URL_LINUX_32="https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux32"
JQ_URL_MACOS="https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64"

fun_download_jq(){
    local path="$PARENT_DIR_PATH/hooks/tools/jq"
    local url=""
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        bit=$(getconf LONG_BIT)
        if (( $bit == 64)); then
            url=$JQ_URL_LINUX_64
        else
            url=$JQ_URL_LINUX_32
        fi
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        url=$JQ_URL_MACOS
    else
        echo "Built-in download url only support Linux and MacOs,\nPelease install jq according to https://stedolan.github.io/jq for other os. "
    fi 
    if [ -n $url ]; then
        echo "Download jq from $url"
        curl -o $path -L $url
        chmod u+x $path
        echo "jq version: $($path --version)"
    fi
}

fun_check_success(){
    local install_jq=$(fun_check_jq)
    if [[ -n $install_jq ]] && [ -L "$WORK_SPACE_PATH/.git/hooks" ]; then
        echo "apply git hook success."
    else    
        echo "apply git hook fail."
    fi
}

fun_check_jq(){
    if [ -x "$(command -v jq)" ]; then
        echo "check jq success, version: $(jq --version)"
    elif [ -x "$PARENT_DIR_PATH/hooks/tools/jq" ]; then
        echo "check jq success, version: $($PARENT_DIR_PATH/hooks/tools/jq --version)"
    fi
}

# 如果不存在 或 不等于 THIS_SHELL_PATH
if [[ ! $GIT_HOOK_APPLAY || "$GIT_HOOK_APPLAY" != "$THIS_SHELL_PATH" ]]; then
    echo "export GIT_HOOK_APPLAY=$THIS_SHELL_PATH" >> "$HOME/.bash_profile"
    export GIT_HOOK_APPLAY=$THIS_SHELL_PATH
fi


if [ ! -d "$WORK_SPACE_PATH/.git" ]; then
    echo "This project don't has git vsc."
    exit $EXIT_NOT_GIT_PROJECT
fi

if [[ -d "$WORK_SPACE_PATH/.git/hooks" && ! -L "$WORK_SPACE_PATH/.git/hooks" ]]; then
    echo "Git has some hooks in .git/hooks, check whether you need them."
    exit $EXIT_HOOK_HAS_EXIST
fi

# 检测是否安装了jq
install_jq=$(fun_check_jq)
if [[ ! -n $install_jq ]] ; then
    fun_download_jq
fi

# 检测并创建软连接
if [ -L "$WORK_SPACE_PATH/.git/hooks" ]; then
    target=$(readlink $WORK_SPACE_PATH/.git/hooks)
    if [ $target!=$"$PARENT_DIR_PATH/hooks" ]; then
        rm -f "$WORK_SPACE_PATH/.git/hooks"
        ln -s "$PARENT_DIR_PATH/hooks" "$WORK_SPACE_PATH/.git/hooks" 
    fi
else
    ln -s "$PARENT_DIR_PATH/hooks" "$WORK_SPACE_PATH/.git/hooks" 
fi

chmod u+x -R "$PARENT_DIR_PATH/hooks"

fun_check_success